package com.example.message_queue.common;

import java.io.*;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-03-27
 * Time:13:49
 * Text：序列化文件
 */
public class BinaryTool{
    //一个对象序列化成一个字节数组
    public static byte[] toBytes(Object object) throws IOException {
        //流对象相当于一个变长的字节数组，将Object序列化写入byteArrayOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){
            //此处的writeObject，将对象进行序列化，生成的二进制数据，写入到objectOutputStream
            //但由于objectOutputStream和byteArrayOutputStream关联，因此写入了byteArrayOutputStream
            objectOutputStream.writeObject(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    //一个字节数组转换为对象序列化
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object=null;
        try(ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(data)){
            try(ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream)) {
                //将data从字节数组读取数据，并且反序列化
                object = objectInputStream.readObject();
            }
        }

        return object;
    }
}
